<?php # 二维码

namespace app\controllers;

use yii;
use yii\web\Controller;
use app\components\BaseController;
use app\models\Fans;
use app\models\Qrcode;
use app\models\Qrcodelist;
use app\models\UploadForm;
// use yii\data\Pagination;
use yii\web\UploadedFile;

class QrcodeController extends BaseController
{
    public $layout = 'main';
    public $enableCsrfValidation = false;

    const UPLOAD_DIR = 'uploads';

    // 二维码每页个数
    const DEFAULT_PAGE_SIZE = 10;

    /**
    * 发布二维码
    */
    public function actionIndex()
    {
        // 当前用户
        $userinfo = $this->getCurrentUser();
        // $userinfo = array('openid' => 'o_HQ5t6Ww1EW8qbRmWF2lJUHWhFE', 'uid' => 1, 'nickname' => 'ta_shuo', 'gender' => 1, 'province' => '福建', 'city' => '厦门', 'headimgurl' => 'http://wx.qlogo.cn/mmopen/rVQIW9nZwdNNibkm1beQlt7eMF45qib7ibsG8dWcgxe7ibnykLOfJMwgmvTvv3oic7plNfdoxOI3RckCYzJRbwheIkvfJZZheEMnc/0');
        // 获取js api配置
        // $js_config = $this->getJsAPIConfig();

        // return $this->render('index', ['userinfo' => $userinfo, 'js_config' => $js_config, 'title' => '上传二维码']);

        return $this->render('index', ['title' => 'upload', 'userinfo' => $userinfo]);
    }

    // 首页二维码列表
    public function actionList()
    {
        // $userinfo = $this->getCurrentUser();
        // var_dump($userinfo);exit;
        // 个人二维码
        $arr_person_qrlist = Qrcodelist::find()
        				->where(['type' => 1])
        				->orderBy('id DESC')
        				->limit(self::DEFAULT_PAGE_SIZE)
        				->all();
        // 群二维码
        $arr_group_qrlist = Qrcodelist::find()
        				->where(['type' => 2])
        				->orderBy('id DESC')
        				->limit(self::DEFAULT_PAGE_SIZE)
        				->all();

        return $this->render('list', ['arr_person_qrlist' => $arr_person_qrlist, 'arr_group_qrlist' => $arr_group_qrlist, 'title' => '人脉']);
    }

    public function actionAjaxlist()
    {
        header("Content-type: text/json; charset=utf-8");
        $type = intval($_GET['type']);
        $page = intval($_GET['page']);
        // $count = intval($_GET['count']) ?: self::DEFAULT_PAGE_SIZE;
        $count = self::DEFAULT_PAGE_SIZE;

        $offset = ($page - 1) * $count;
        $list = Qrcodelist::find()
        		->where(['type' => $type])
        		->orderBy('id DESC')
        		->offset($offset)
        		->limit($count)
        		->all();

         foreach($list as $k => $v) {
             $list[$k] = $v->toArray();
         }
         echo json_encode($list);
    }

    // 图片上传
    public function actionUpload()
    {
        // 判断是否登录
        $userinfo = $this->getCurrentUser(false);
        // $userinfo = array('openid' => 'ewgregwrr342354dewf2f');
        if(!empty($userinfo)) {
        	$current_time = time();
        	$data = $_POST['data'];
        	$type = intval($_POST['type']);
        	$description = $_POST['description'];
        	$data = substr($data, strlen('data:image/png;base64,'));
        	$file = base64_decode($data);
        	$path = realpath('.').'/'.self::UPLOAD_DIR.'/'.$current_time;
        	file_put_contents($path, $file);
	
        	$image_mime = image_type_to_mime_type(exif_imagetype($path));
        	$new_filename = $path.'.'.substr($image_mime, strpos($image_mime, '/')+1);
        	rename($path, $new_filename);
	
	// 如果不存在该用户则插入user表
	if(!isset($userinfo['uid'])) {
	    $fans = new Fans();
	    $fans->openid = $userinfo['openid'];
	    $fans->score = 10;

	    if($fans->save()) {
	        $userinfo['uid'] = Yii::$app->db->getLastInsertID();
	        $this->setCurrentUser($userinfo);
	    }else {

	    }
	}

	// 插入qrcode表
        	$qrcode = new Qrcode();
        	$qrcode->uid = $userinfo['uid'];
        	$qrcode->location = substr($new_filename, strrpos($new_filename, '/')+1);
        	$qrcode->description = $description;
        	$qrcode->type = $type;
        	$qrcode->upload_at = $current_time;
        	$qrcode->create_at = 0;
        	$qid = 0;
        	if($qrcode->save()) {
        	    $qid = Yii::$app->db->getLastInsertID();
        	}

        	// 返回插入二维码自增id
        	echo $qid;
        }
    }

    // 发布二维码
    public function actionCreate()
    {
        // 判断是否登录
        $userinfo = $this->getCurrentUser(false);
        // $userinfo = array('openid' => 'o_HQ5t6Ww1EW8qbRmWF2lJUHWhFE', 'uid' => 1, 'nickname' => 'ta_shuo', 'gender' => 1, 'province' => '福建', 'city' => '厦门', 'headimgurl' => 'http://wx.qlogo.cn/mmopen/rVQIW9nZwdNNibkm1beQlt7eMF45qib7ibsG8dWcgxe7ibnykLOfJMwgmvTvv3oic7plNfdoxOI3RckCYzJRbwheIkvfJZZheEMnc/0');
        if(!empty($userinfo) && !empty($_POST)) {
        	$current_time = time();
        	$qid = $_POST['qid'];

        	$qrcode = Qrcode::findOne($qid);
        	if(!empty($qrcode)) {
        	    $qrcode->create_at = $current_time;

        	    // 发布成功后需插入到二维码列表中
        	    if($qrcode->save()) {
        	        $qrcodelist = new Qrcodelist();
        	        $qrcodelist->uid = $userinfo['uid'];
        	        $qrcodelist->username = $userinfo['nickname'];
        	        $qrcodelist->avatar = $userinfo['headimgurl'];
        	        $qrcodelist->gender = $userinfo['sex'];
        	        $qrcodelist->qrcode = $qrcode->location;
        	        $qrcodelist->type = $qrcode->type;
        	        $qrcodelist->description = $qrcode->description;
        	        $qrcodelist->province = $userinfo['province'];
        	        $qrcodelist->city = $userinfo['city'];
        	        $qrcodelist->status = 1;
        	        
        	        if($qrcodelist->save()) {
        	        	echo 1;
        	        }
        	    }else {
        	        echo 0;
        	    }
        	}
        }
    }

	/**验证token
	 * @Author: magic
	 * @Date: 2016-
	 * @return bool
	 */
	public function actionCheck()
	{
		$echoStr = $_GET["echostr"];

		//valid signature , option
		if($this->checkSignature()){
			echo $echoStr;
			exit;
		}
	}


	public function responseMsg()
	{
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

		//extract post data
		if (!empty($postStr)){
			/* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
               the best way is to check the validity of xml by yourself */
			libxml_disable_entity_loader(true);
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$fromUsername = $postObj->FromUserName;
			$toUsername = $postObj->ToUserName;
			$keyword = trim($postObj->Content);
			$time = time();
			$textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";
			if(!empty( $keyword ))
			{
				$msgType = "text";
				$contentStr = "Welcome to wechat world!";
				$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
				echo $resultStr;
			}else{
				echo "Input something...";
			}

		}else {
			echo "";
			exit;
		}
	}

	private function checkSignature()
	{


		$signature = $_GET["signature"];
		$timestamp = $_GET["timestamp"];
		$nonce = $_GET["nonce"];

		$token = 'bmob';
		$tmpArr = array($token, $timestamp, $nonce);
		// use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );

		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}